import pandas
import yaml

from get_project_path import project_path


def read_excel(filepath, sheet_name):
    """
    读取excel文件
    :param filepath:
    :param sheet_name:
    :return:
    """
    # keep_default_na该参数默认值是True，意思是读取空单元格时结果是na，na咱在后续不好处理，
    # 所以我们把他设置为Fasle,那么空单元格读取后就是空字符串
    # engine表单pandas在读取excel时使用的底层引擎，所以在装pandas还得openpyxl
    res = pandas.read_excel(f'{project_path}{filepath}', sheet_name=sheet_name, keep_default_na=False,
                            engine='openpyxl')
    # print(res)
    # res结果数据格式不符合pytest参数化时要求的数据格式，因此我们要做数据转换
    # 目前来说我们的pytest的数据格式是一个二维列表，所以我们解析res将其转成二维列表

    lines_count = res.shape[0]  # 获取总行数
    cols_count = res.shape[1]  # 获取总列数
    # data就是用来存储我们转换之后的结果的数据的
    data = []
    for l in range(lines_count):
        line = []  # 这是存储当前行所有单元格的数据列表
        for c in range(cols_count):
            cell_data = res.iloc[l, c]  # 根据行和列得到某个单元格的数据
            line.append(cell_data)
        data.append(line)
    return data


def load_yaml_file(filepath):
    """
    读取yaml文件
    :param filepath:
    :return:
    """
    with open(file=f'{project_path}{filepath}', mode='r', encoding='UTF-8') as f:
        content = yaml.load(f, Loader=yaml.FullLoader)
        return content


def write_yaml(filepath, content):
    """
    写入yaml文件
    :param filepath:
    :param content:
    :return:
    """
    with open(file=f'{project_path}{filepath}', mode='w', encoding='UTF-8') as f:
        yaml.dump(content, f, Dumper=yaml.Dumper)


def read_txt(filepath):
    """
    读取txt文件
    :param filepath:
    :return:
    """
    with open(file=f'{project_path}{filepath}', mode='r', encoding='UTF-8') as file:
        content = file.read()
        return content


def write_txt(filepath, content):
    """
    写入txt文件
    :param filepath:
    :return:
    a: 追加
    w: 覆盖
    r: 读取
    """
    with open(file=f'{project_path}{filepath}', mode='a', encoding='UTF-8') as file:
        file.write(content)


if __name__ == '__main__':
    # print(read_excel('/data/mtxshop_testdata.xlsx', '立即购买接口测试数据'))
    # print(load_yaml_file('/data/mtxshop_testdata.yml'))
    # content = load_yaml_file('/config/env_prepro.yml')['http']
    # write_yaml('/config/http.yml', content)

    # name = "Alice"
    # age = 30
    # message_parts = ["My name is", name, "and I am", str(age), "years old."]
    # print(message_parts)
    # message = " ".join(message_parts)
    # print(message)
    content = load_yaml_file('/config/env_prepro.yml')['http']
    print(content)
    write_txt('/config/re_test.txt', content)